using System.Collections.Specialized;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Wechat.Crawler.Blog;
using Wechat.Crawler.Toptic;
using Wechat.Service.Browser;
using Wechat.Service.Convert;
using Wechat.Service.Extractor;
using Wechat.Service.Filter;
using Wechat.Settings;

namespace Wechat.Service.Articles;

public class ArticleService : IArticleService
{
    private readonly IConfiguration _configuration;
    private readonly IBrowserService _browserService;
    private readonly IExtractorService _extractorService;
    private readonly IConvertService _convertService;
    private readonly IFilterService _filterService;
    private readonly IConfigurationSection _wechatFolderSection;
    private readonly List<string> _urls = [];
    private readonly WechatDbContext _wechatDbContext;

    private readonly ILogger<ArticleService> _logger;

    public ArticleService(
        IBrowserService browserService,
        IConfiguration configuration,
        IExtractorService extractorService,
        IFilterService filterService,
        IConvertService convertService,
        WechatDbContext wechatDbContext,
        ILogger<ArticleService> logger
    )
    {
        _browserService = browserService;
        _configuration = configuration;
        _extractorService = extractorService;
        _filterService = filterService;

        _wechatFolderSection =
            _configuration.GetSection(AppSettings.WechatFolder) ?? throw new Exception($"{AppSettings.WechatFolder}在appsettings.json没有发现");
        _convertService = convertService;
        _wechatDbContext = wechatDbContext;
        _logger = logger;
    }

    public void SaveArticlesToOneTxtFromCollectionArticleUrl(string url)
    {
        throw new NotImplementedException();
    }

    public void SaveArticlesToTxtFromCollectionArticleUrl(string url)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 通过作者整理的文件链接合集,下载所有列出的文章
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    async Task<string> IArticleService.SaveArticlesToHtmlFromCollectionArticleUrl(string url)
    {
        string html = await _browserService.DownLoadRawPageByGetRequest(url);
        // extractor links --------------------------------------
        var links = _extractorService.ExtractLinksFromHtml(html);
        if (links.Count == 0)
            return string.Empty;
        if (links.Count == 1)
        {
            var tempLink = links.First().Replace("http://", "").Replace("https://", "");
            if (tempLink == url.Replace("http://", "").Replace("https://", "").Substring(0, tempLink.Count()))
                return string.Empty;
        }

        string randowFolderName = string.Empty;
        var i = 1;
        foreach (var link in links)
        {
            Console.WriteLine($"{i++}_{link}");
            if (randowFolderName == string.Empty)
                randowFolderName = await SaveArticleByUrl(link);
            await SaveArticleByUrl(link, randowFolderName);
            await Task.Delay(5);
        }
        return randowFolderName;
    }

    public async Task<string> SaveArticleByUrl(string url, string? randomFolderName = null)
    {
        var outFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
        (string folderName, string fileName, string html) = await _browserService.DownLoadPageByGetRequest(url);
        if (randomFolderName == null)
            randomFolderName = folderName + Path.GetRandomFileName();
        var folderPath = Path.Combine(outFolder, randomFolderName);
        if (!Directory.Exists(folderPath))
            Directory.CreateDirectory(folderPath);
        var filePath = Path.Combine(folderPath, fileName);
        File.WriteAllText(filePath, html);
        return randomFolderName;
    }

    public async Task FilterArticlesByBizFolderAsync(string biz)
    {
        var outFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
        var filterFolder = _wechatFolderSection.GetSection(AppSettings.FilterFolder).Value!;
        if (!Directory.Exists(filterFolder))
            Directory.CreateDirectory(filterFolder);
        if (!Directory.Exists(Path.Combine(filterFolder, biz)))
            Directory.CreateDirectory(Path.Combine(filterFolder, biz));
        // System.Console.WriteLine(outFolder);
        // System.Console.WriteLine(Path.Combine(outFolder,biz));
        var articleFolder = Path.Combine(outFolder, biz);
        System.Console.WriteLine(biz);
        System.Console.WriteLine(articleFolder);
        // throw new Exception("---------------");
        // System.Console.WriteLine(articleFolder);
        // 使用DirectoryInfo和FileInfo来获取文件信息
        DirectoryInfo di = new DirectoryInfo(articleFolder);
        FileInfo[] files = di.GetFiles("*.html"); // 使用通配符*.html来筛选所有HTML文件
        // 遍历所有找到的文件
        foreach (FileInfo file in files)
        {
            // 在这里，您可以对每个文件执行操作，例如打印文件名
            Console.WriteLine(file.FullName);
            var content = await _filterService.FilterByArticlePathAsync(file.FullName);
            // Console.WriteLine(content);
            // Console.WriteLine(filterFolder);
            // Console.WriteLine(file.Name);
            // Console.WriteLine(Path.Combine(filterFolder,biz,file.Name));
            var fileNewPath = Path.Combine(filterFolder, biz, file.Name);
            File.WriteAllText(fileNewPath, content);
        }
    }

    public void ConvertArticlesToOneTextByBiz(string biz, string name)
    {
        var filterFolder = _wechatFolderSection.GetSection(AppSettings.FilterFolder).Value!;
        var articleFolder = Path.Combine(filterFolder, biz);
        // 使用DirectoryInfo和FileInfo来获取文件信息
        DirectoryInfo di = new DirectoryInfo(articleFolder);
        FileInfo[] files = di.GetFiles("*.html"); // 使用通配符*.html来筛选所有HTML文件
        var filePathList = files.Select(x => x.FullName).Order().ToList();
        // 遍历所有找到的文件
        _convertService.ConvertToOneText(filePathList, name);
        // Console.WriteLine(filterFolder);
        // System.Console.WriteLine(articleFolder);
        // Console.WriteLine(Path.Combine(filterFolder,biz));
        // Console.WriteLine(biz);
        // Console.WriteLine(name);
    }

    public void ConvertArticlesToOneTextByBizWithFilter(string biz, string name)
    {
        var filterFolder = _wechatFolderSection.GetSection(AppSettings.FilterFolder).Value!;
        var articleFolder = Path.Combine(filterFolder, biz);
        // 使用DirectoryInfo和FileInfo来获取文件信息
        DirectoryInfo di = new DirectoryInfo(articleFolder);
        FileInfo[] files = di.GetFiles("*.html"); // 使用通配符*.html来筛选所有HTML文件
        var filePathList = files.Select(x => x.FullName).ToList();
        // 遍历所有找到的文件
        _convertService.ConvertToOneTextWithFilter(filePathList, name);
        // Console.WriteLine(filterFolder);
        // System.Console.WriteLine(articleFolder);
        // Console.WriteLine(Path.Combine(filterFolder,biz));
        // Console.WriteLine(biz);
        // Console.WriteLine(name);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task<string> SaveArticlesToHtmlFromTopticUrl(string url)
    {
        Uri myUri = new(url.Replace("&amp;", "&"));
        NameValueCollection originalQueryCollection = HttpUtility.ParseQueryString(myUri.Query);
        string? biz = originalQueryCollection.Get("__biz") ?? throw new Exception("biz isn null");
        string? albumId = originalQueryCollection.Get("album_id") ?? throw new Exception("albumid isn null");
        string html = await _browserService.DownLoadRawPageByGetRequest(url);
        var links = await _extractorService.ExtractLinksFromTopicHtmlAsync(html);
        var lastUrl = links.LastOrDefault() ?? throw new Exception("last url is null");
        _urls.AddRange(links);
        // System.Console.WriteLine(_urls.Count);
        // System.Console.WriteLine(lastUrl);
        await this.RequestTopicUrlsByTopicUrl(lastUrl, albumId, biz);
        string randowFolderName = string.Empty;
        System.Console.WriteLine(_urls.Count);
        var i = 0;
        foreach (var link in _urls)
        {
            System.Console.WriteLine($"index = {i++}");
            if (randowFolderName == string.Empty)
                randowFolderName = await SaveArticleByUrl(link);
            await SaveArticleByUrl(link, randowFolderName);
            await Task.Delay(1000);
        }
        return randowFolderName;
    }

    /// <summary>
    /// 通过topic界面的url获取所有的urls,是一个递归函数
    /// </summary>
    /// <param name="url"></param>
    /// <param name="albumId"></param>
    /// <param name="biz"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task RequestTopicUrlsByTopicUrl(string url, string albumId, string biz)
    {
        if (url == null)
            return;
        NameValueCollection lastUrlQueryCollection = HttpUtility.ParseQueryString(url);
        string? mid = lastUrlQueryCollection.Get("mid");
        string? idx = lastUrlQueryCollection.Get("idx");
        string newUrl = this.GenerateTopticRequestUrl(biz, albumId, mid, idx);
        var topicUrlResponse = await GetTopticUrls(newUrl);
        System.Console.WriteLine(newUrl);
        await Task.Delay(3000);
        if (topicUrlResponse.GetAlbumResp.ArticleList == null)
            return;
        List<string> articleList = topicUrlResponse.GetAlbumResp.ArticleList.Select(x => x.Url).ToList();
        _urls.AddRange(articleList);
        var articleCount = topicUrlResponse.GetAlbumResp.ArticleList.Count;
        if (articleCount < 10)
            return;
        var lastUrl = topicUrlResponse.GetAlbumResp.ArticleList?.LastOrDefault()?.Url ?? throw new Exception("last url is null");
        await this.RequestTopicUrlsByTopicUrl(lastUrl, albumId, biz);
    }

    public string GenerateTopticRequestUrl(string? biz, string? albumdId, string? newMid, string? idx)
    {
        // 创建一个空的查询字符串实例
        NameValueCollection newQueryCollection = HttpUtility.ParseQueryString(string.Empty);
        // 添加参数
        newQueryCollection.Add("__biz", biz);
        newQueryCollection.Add("action", "getalbum");
        newQueryCollection.Add("album_id", albumdId);
        newQueryCollection.Add("count", "10");
        newQueryCollection.Add("begin_msgid", newMid);
        newQueryCollection.Add("begin_itemidx", idx);
        newQueryCollection.Add("appmsg_token", "");
        newQueryCollection.Add("x5", "0");
        newQueryCollection.Add("f", "json");
        // 将查询字符串转换为字符串形式
        string? newQuery = newQueryCollection.ToString();
        var newUrl = $"https://mp.weixin.qq.com/mp/appmsgalbum?{newQuery}";
        return newUrl;
    }

    private static async Task<ResponseDto> GetTopticUrls(string newUrl)
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri(newUrl),
            Headers =
            {
                {
                    "User-Agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0"
                }
            }
        };
        var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        // System.Console.WriteLine(body);
        // 反序列化JSON字符串到DTO对象
        ResponseDto responseDto = JsonConvert.DeserializeObject<ResponseDto>(body) ?? throw new Exception($"{newUrl}请求错误");
        return responseDto;
    }

    public async Task SaveArticleUrlFromCollectionArticleUrlNew(string url, string title)
    {
        string html = await _browserService.DownLoadRawPageByGetRequest(url);
        // extractor links --------------------------------------
        var links = _extractorService.ExtractLinksFromHtml(html);
        if (links.Count == 0)
        {
            System.Console.WriteLine("文章中没有检测一个超链接,请检查");
            _logger.LogWarning("文章中没有检测一个超链接,请检查");
            return;
        }

        if (links.Count == 1)
        {
            var tempLink = links.First().Replace("http://", "").Replace("https://", "");
            if (tempLink == url.Replace("http://", "").Replace("https://", "").Substring(0, tempLink.Count()))
            {
                System.Console.WriteLine("文章中没有检测一个超链接,请检查");
                _logger.LogWarning("文章中没有检测一个超链接,请检查");
                return;
            }
        }

        List<CollectionArticle> collectionArticles = _wechatDbContext
            .CollectionArticle.Where(item => item.CollectionUrl == url && item.Title == title)
            .ToList();

        if (collectionArticles.Count() >= links.Count())
        {
            System.Console.WriteLine("文章中的链接已经全部存在，无需更新");
            _logger.LogInformation("文章中的链接已经全部存在，无需更新");
            return;
        }

        var folderName = Path.GetRandomFileName();

        foreach (var link in links)
        {
            (string biz, long mid, int idx) = HandleUrl(link.Replace("%3d", "="));

            if (
                _wechatDbContext
                    .CollectionArticle.Where(x => x.Mid == mid && x.Url == link && x.Biz == biz && x.CollectionUrl == url && x.Title == title)
                    .FirstOrDefault() != null
            )
            {
                System.Console.WriteLine($"mid = {mid}的link已经存在,跳过");
                _logger.LogInformation($"mid = {mid}的link已经存在");
                continue;
            }

            _wechatDbContext.CollectionArticle.Add(
                new CollectionArticle
                {
                    Biz = biz,
                    Mid = mid,
                    Idx = idx,
                    Url = link,
                    Title = title,
                    CollectionUrl = url,
                    FolderName = folderName
                }
            );

            _wechatDbContext.SaveChanges();
        }
    }

    public async Task<string> SaveArticleUrlFromCollectionArticleUrl(string url, string title)
    {
        string html = await _browserService.DownLoadRawPageByGetRequest(url);

        // extractor links --------------------------------------
        var links = _extractorService.ExtractLinksFromHtml(html);
        if (links.Count == 0)
            return string.Empty;

        if (links.Count == 1)
        {
            var tempLink = links.First().Replace("http://", "").Replace("https://", "");
            if (tempLink == url.Replace("http://", "").Replace("https://", "").Substring(0, tempLink.Count()))
                return string.Empty;
        }

        var i = 1;
        var randomSuffix = Path.GetRandomFileName();

        foreach (var link in links)
        {
            System.Console.WriteLine($"{i++}_{link}");
            (string biz, long mid, int idx) = HandleUrl(link.Replace("%3d", "="));
            if (_wechatDbContext.TopicArticles.Where(x => x.Mid == mid).FirstOrDefault() != null)
                continue;
            _wechatDbContext.TopicArticles.Add(
                new TopicArticle
                {
                    Biz = biz + randomSuffix,
                    Mid = mid,
                    Url = link,
                    Title = title
                }
            );
            _wechatDbContext.SaveChanges();
        }

        // System.Console.WriteLine($"{title}的相关链接已经添加到数据库,bizsuffix={randomSuffix}");
        string? rawFolderName = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value ?? throw new Exception($"{AppSettings.RawFolder}为空");
        (string b, long _, int _) = HandleUrl(links.First().Replace("%3d", "="));
        var folderPath = Path.Combine(rawFolderName, b + randomSuffix);
        if (!Directory.Exists(folderPath))
            Directory.CreateDirectory(folderPath);
        System.Console.WriteLine(folderPath);
        // 指定文本文件的路径
        string filePath = Path.Combine(folderPath, "desp.txt");
        // 使用StreamWriter打开文件
        using StreamWriter writer = new StreamWriter(filePath);
        // 逐行写入内容
        writer.WriteLine(b + randomSuffix);
        writer.WriteLine(title);
        return b + randomSuffix;
    }

    private static (string biz, long mid, int idx) HandleUrl(string url)
    {
        string patternUrl = @"(?<key>\w+)=(?<value>[^&]+)";
        var paramMatches = Regex.Matches(url, patternUrl);
        string biz = string.Empty;
        long mid = 0;
        int idx = 0;
        foreach (Match m in paramMatches)
        {
            string key = m.Groups["key"].Value;
            if (key == "sn" || key == "chksm" || key == "scene")
                continue;
            string value = m.Groups["value"].Value;
            if (key == "__biz")
            {
                biz = value;
            }
            if (key == "mid")
            {
                mid = long.Parse(value);
            }
            if (key == "idx")
            {
                idx = int.Parse(value);
            }
        }
        if (biz == string.Empty || mid == 0)
        {
            return ("", 0, 0);
        }
        return (biz, mid, idx);
    }

    public async Task DownloadArticlesFromDb(string uniqueBiz)
    {
        List<TopicArticle> topicArticles = _wechatDbContext.TopicArticles.Where(x => x.Biz == uniqueBiz && x.IsDownload == false).ToList();
        var outFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
        if (topicArticles.Count() == 0)
            return;
        var biz = topicArticles.First().Biz;
        foreach (var article in topicArticles)
        {
            try
            {
                (string folderName, string fileName, string html) = await _browserService.DownLoadPageByGetRequest(article.Url!);
                var folderPath = Path.Combine(outFolder, article.Biz!);
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);
                var filePath = Path.Combine(folderPath, fileName);
                File.WriteAllText(filePath, html);
                article.IsDownload = true;
                _wechatDbContext.SaveChanges();
                System.Console.WriteLine(uniqueBiz);
            }
            catch (System.Exception)
            {
                System.Console.WriteLine("下来失败的url: ");
                System.Console.WriteLine(article.Url);
                continue;
            }
        }
    }

    public async Task DownloadArticlesFromCollectionUrlAndTitle(string url, string title)
    {
        List<CollectionArticle> collectionArticles = _wechatDbContext
            .CollectionArticle.Where(x => x.Title == title && x.CollectionUrl == url && !x.IsDownload)
            .ToList();

        var idx = 0;
        foreach (var collectionArticle in collectionArticles)
        {
            System.Console.WriteLine($"{idx++}_{collectionArticle.Mid}");

            var outFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
            var folderPath = Path.Combine(outFolder, collectionArticle.FolderName!);

            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);

            (string html, string articleTitle, bool isOriginal) = await _browserService.DownLoadModifyPageByGetRequest(collectionArticle.Url!);

            if (string.IsNullOrEmpty(html) || string.IsNullOrEmpty(articleTitle))
            {
                System.Console.WriteLine($"Mid = {collectionArticle.Mid}下载失败,跳过");
                continue;
            }
            var filePath = Path.Combine(folderPath, $"{collectionArticle.Mid.ToString()!}_{idx.ToString()}_{articleTitle}.html");
            File.WriteAllText(filePath, html);
            collectionArticle.IsDownload = true;
            _wechatDbContext.SaveChanges();
            System.Console.WriteLine($"{collectionArticle.Mid.ToString()!}_{idx.ToString()}_{articleTitle}.html_下载完成");
        }
    }

    public async Task FilterArticlesByCollectionUrlAndTitleAsync(string url, string title)
    {
        List<CollectionArticle> collectionArticles = _wechatDbContext
            .CollectionArticle.Where(x => x.Title == title && x.CollectionUrl == url && x.IsDownload == false)
            .ToList();
        if (collectionArticles.Count > 0)
        {
            System.Console.WriteLine("系列还有文章没有下载完成，请重新下载；");
            return;
        }

        string? folderName = _wechatDbContext
            .CollectionArticle.Where(x => x.Title == title && x.CollectionUrl == url)
            .Select(x => x.FolderName)
            .First();

        var rawFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
        var rawfolderPath = Path.Combine(rawFolder, folderName!);

        var filterFolder = _wechatFolderSection.GetSection(AppSettings.FilterFolder).Value!;
        if (!Directory.Exists(filterFolder))
            Directory.CreateDirectory(filterFolder);

        DirectoryInfo di = new DirectoryInfo(rawfolderPath);
        FileInfo[] files = di.GetFiles("*.html"); // 使用通配符*.html来筛选所有HTML文件

        var i = 0;
        // 遍历所有找到的文件
        foreach (FileInfo file in files)
        {
            System.Console.WriteLine($"{i++}_{file.Name}");
            // 在这里，您可以对每个文件执行操作，例如打印文件名
            var content = await _filterService.FilterByArticlePathAsync(file.FullName);
            var newContent = _filterService.ReplaceHtmlHref(content);

            // var content = await _filterService.FilterByArticlePathAsync("D:/Code/Wechat.CrawlerNew/Article/Output/Raw/1j3teg3h.z1x/2247495872.html");

            var filterFolderPath = Path.Combine(filterFolder, folderName!);
            if (!Directory.Exists(filterFolderPath))
                Directory.CreateDirectory(filterFolderPath);

            var filterFilePath = Path.Combine(filterFolderPath, file.Name);
            System.Console.WriteLine(filterFilePath);
            File.WriteAllText(filterFilePath, newContent);
        }
    }

    public void ConvertArticlesToOneTextByCollectionUrlAndTitleAsync(string url, string title)
    {
        string? folderName = _wechatDbContext
            .CollectionArticle.Where(x => x.Title == title && x.CollectionUrl == url)
            .Select(x => x.FolderName)
            .First();

        var filterFolder = _wechatFolderSection.GetSection(AppSettings.FilterFolder).Value!;
        var filterFolderPath = Path.Combine(filterFolder, folderName!);
        DirectoryInfo di = new DirectoryInfo(filterFolderPath);
        FileInfo[] files = di.GetFiles("*.html"); // 使用通配符*.html来筛选所有HTML文件
        var filePathList = files.Select(x => x.FullName).Order().ToList();
        // 遍历所有找到的文件
        _convertService.ConvertToOneText(filePathList, title);
    }

    public void ConvertArticlesToOnePDFByCollectionUrlAndTitleAsync(string url, string title)
    {
        string? folderName = _wechatDbContext
            .CollectionArticle.Where(x => x.Title == title && x.CollectionUrl == url)
            .Select(x => x.FolderName)
            .First();

        var filterFolder = _wechatFolderSection.GetSection(AppSettings.FilterFolder).Value!;
        var filterFolderPath = Path.Combine(filterFolder, folderName!);
        DirectoryInfo di = new DirectoryInfo(filterFolderPath);
        FileInfo[] files = di.GetFiles("*.html"); // 使用通配符*.html来筛选所有HTML文件
        var filePathList = files.Select(x => x.FullName).Order().ToList();
        // 遍历所有找到的文件
        _convertService.ConvertToOnePDF(filePathList, title);
    }

    public async Task DownloadArticlesFromByBiz(string biz)
    {
        List<Article> articles = _wechatDbContext.Articles.Where(x => x.IsDownload == false && x.Biz == biz).ToList();
        if (articles.Count == 0)
        {
            System.Console.WriteLine("全部文章下载完成!");
        }

        var outFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
        // System.Console.WriteLine(outFolder);
        // System.Console.WriteLine(Path.Combine(outFolder,biz));
        var wechatOutFolder = Path.Combine(outFolder, biz);
        if (!Directory.Exists(wechatOutFolder))
            Directory.CreateDirectory(wechatOutFolder);

        foreach (var article in articles)
        {
            (string html, string articleTitle, bool isOriginal) = await _browserService.DownLoadModifyPageByGetRequest(article.Url!);

            if (string.IsNullOrEmpty(html) || string.IsNullOrEmpty(articleTitle))
            {
                System.Console.WriteLine($"Mid = {article.Mid}下载失败,跳过");
                continue;
            }
            var filePath = Path.Combine(wechatOutFolder, $"{article.Mid.ToString()!}_{article.Idx.ToString()}_{articleTitle}.html");
            File.WriteAllText(filePath, html);
            article.IsDownload = true;
            _wechatDbContext.SaveChanges();
            System.Console.WriteLine($"{article.Mid.ToString()!}_{article.Idx.ToString()}_{articleTitle}.html_下载完成");
        }
    }

    public async Task GetArticleUrlsFromLocalAsync()
    {
        var filterFolder = _wechatFolderSection.GetSection(AppSettings.InputFolder).Value!;

        string[] files = Directory.GetFiles(filterFolder, "*.*", SearchOption.AllDirectories);

        foreach (string file in files)
        {
            System.Console.WriteLine(file);
            // 使用StreamReader读取文件
            using StreamReader reader = new StreamReader(file, Encoding.UTF8); // 这里假设文件编码为UTF8
            // 读取文件全部内容
            string htmlContent = reader.ReadToEnd();
            // 解析HTML内容
            var document = await new HtmlParser().ParseDocumentAsync(htmlContent);
            IHtmlCollection<IElement> elements = document.QuerySelectorAll("h4.weui_media_title");

            foreach (var element in elements)
            {
                string? link = element.GetAttribute("hrefs");
                if (string.IsNullOrEmpty(link))
                    continue;

                Uri myUri = new(link.Replace("&amp;amp;", "&").Replace("&amp;", "&"));

                NameValueCollection originalQueryCollection = HttpUtility.ParseQueryString(myUri.Query);
                string? biz = originalQueryCollection.Get("__biz");
                string? mid = originalQueryCollection.Get("mid");
                string? idx = originalQueryCollection.Get("idx");
                string? sn = originalQueryCollection.Get("sn");
                System.Console.WriteLine($"biz = {biz}, mid= {mid}, idx={idx}, sn = {sn}");

                if (string.IsNullOrEmpty(biz) || string.IsNullOrEmpty(mid) || string.IsNullOrEmpty(idx) || string.IsNullOrEmpty(sn))
                    continue;
                List<Article> articles = _wechatDbContext
                    .Articles.Where(x => x.Mid == long.Parse(mid) && x.Biz == biz && x.Idx == int.Parse(idx) && x.Url == link)
                    .ToList();
                if (articles.Count > 0)
                {
                    System.Console.WriteLine($"跳过：mid = {mid},idx = {idx}");
                    continue;
                }

                _wechatDbContext.Articles.Add(
                    new Article
                    {
                        Mid = long.Parse(mid),
                        Biz = biz,
                        Idx = int.Parse(idx),
                        Url = link
                    }
                );
                _wechatDbContext.SaveChanges();
                System.Console.WriteLine($"添加：mid = {mid},idx = {idx}添加成功");
            }
        }
        System.Console.WriteLine("link收集完毕");
    }

    public async Task FilterArticlesByBiz(string biz)
    {
        var outFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
        var wechatOutFolder = Path.Combine(outFolder, biz);
    }

    public async Task MergerArticlesByBiz(string biz)
    {
        var txtFolder =
            _wechatFolderSection.GetSection(AppSettings.TxtFolder).Value ?? throw new Exception($"{AppSettings.TxtFolder}在appsettings.json没有发现");

        if (!Directory.Exists(txtFolder))
            Directory.CreateDirectory(txtFolder);

        System.Console.WriteLine("输入文件名称:");
        Console.InputEncoding = Encoding.Unicode;
        Console.OutputEncoding = Encoding.Unicode;
        string? inputFileName = System.Console.ReadLine();
        if (string.IsNullOrEmpty(inputFileName))
        {
            System.Console.WriteLine("必须输入文件名称");
            return;
        }

        var txtPath = Path.Combine(txtFolder, inputFileName + ".txt");

        using StreamWriter writer = new StreamWriter(txtPath);

        var outFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
        var wechatOutFolder = Path.Combine(outFolder, biz);
        string[] files = Directory.GetFiles(wechatOutFolder, "*.*", SearchOption.AllDirectories);
        List<string> sortedFiles = files
            .OrderBy(file =>
            {
                string[] fileNames = Path.GetFileName(file).Split("_");
                return long.Parse(fileNames[0] + fileNames[1]);
            })
            .ToList();

        var i = 1;
        foreach (string file in sortedFiles)
        {
            // 使用StreamReader读取文件
            string content = await _extractorService.ExtractContentFromHtmlByPathAsync(file);
            string title = await _extractorService.ExtractTitleFromHtmlByPathAsync(file);

            writer.WriteLine($"第{i}章");
            writer.WriteLine(title.Trim());
            System.Console.WriteLine($"{i}_{title}");
            string formatContent = _filterService.FormatContent(content);
            writer.WriteLine(formatContent);
            i++;
        }
    }

    public async Task ConvertArticleUrlsToText()
    {
        var txtFolder =
            _wechatFolderSection.GetSection(AppSettings.TxtFolder).Value ?? throw new Exception($"{AppSettings.TxtFolder}在appsettings.json没有发现");

        if (!Directory.Exists(txtFolder))
            Directory.CreateDirectory(txtFolder);

        System.Console.WriteLine("输入文件名称:");
        Console.InputEncoding = Encoding.Unicode;
        Console.OutputEncoding = Encoding.Unicode;
        string? inputFileName = System.Console.ReadLine();
        if (string.IsNullOrEmpty(inputFileName))
        {
            System.Console.WriteLine("必须输入文件名称");
            return;
        }

        var txtPath = Path.Combine(txtFolder, inputFileName + ".txt");

        using StreamWriter writer = new StreamWriter(txtPath);

        List<Article> articles = _wechatDbContext.Articles.ToList();
        foreach (var artile in articles)
        {
            writer.WriteLine(artile.Url);
        }
    }

    public async Task DownloadOriginalArticlesFromByBiz(string biz)
    {
        List<Article> articles = _wechatDbContext.Articles.Where(x => x.IsDownload == false && x.Biz == biz && x.DelFlag == false).ToList();
        System.Console.WriteLine(articles.Count);

        // List<Article> articles = _wechatDbContext.Articles.Where(x =>x.Biz == biz).ToList();
        if (articles.Count == 0)
        {
            System.Console.WriteLine("全部文章下载完成!");
        }
        var outFolder = _wechatFolderSection.GetSection(AppSettings.RawFolder).Value!;
        // System.Console.WriteLine(outFolder);
        // System.Console.WriteLine(Path.Combine(outFolder,biz));
        var wechatOutFolder = Path.Combine(outFolder, biz);
        if (!Directory.Exists(wechatOutFolder))
            Directory.CreateDirectory(wechatOutFolder);

        foreach (var article in articles)
        {
            if (article.FailCount > 3)
            {
                continue;
            }
            (string html, string articleTitle, bool isOriginal) = await _browserService.DownLoadModifyPageByGetRequest(article.Url!);

            if (string.IsNullOrEmpty(html) || string.IsNullOrEmpty(articleTitle))
            {
                System.Console.WriteLine($"Mid = {article.Mid},第 {article.FailCount} 次下载失败,跳过");
                System.Console.WriteLine(article.Url);
                if (article.FailCount == null)
                {
                    article.FailCount = 0;
                }
                else
                {
                    article.FailCount = article.FailCount + 1;
                }
                if (html == "此内容因违规无法查看")
                {
                    System.Console.WriteLine("此内容因违规无法查看");
                    article.DelFlag = true;
                }
                _wechatDbContext.SaveChanges();
                continue;
            }

            var originalPrefix = isOriginal ? "非原创" : "原创";
            var filePath = Path.Combine(wechatOutFolder, $"{article.Mid.ToString()!}_{article.Idx.ToString()}_{originalPrefix}_{articleTitle}.html");

            File.WriteAllText(filePath, html);
            article.IsDownload = true;
            _wechatDbContext.SaveChanges();
            System.Console.WriteLine($"{article.Mid.ToString()!}_{article.Idx.ToString()}_{originalPrefix}_{articleTitle}.html");
        }
    }

    public async Task GetArticleUrlsFromRequestAsync()
    {
        var latestTxtFilePath = GetLatestTxtFilePathV2();
        // var latestTxtFilePath = @"D:\Code\Wechat.CrawlerNew\FiddlerRequest\226_Request.txt";

        string htmlContent = File.ReadAllText(latestTxtFilePath);

        (string biz, string uin, string pass_ticket, string key, string appmsg_token) = ExtractParametersV2(htmlContent);
        // System.Console.WriteLine("biz=" + biz);
        // System.Console.WriteLine("uin=" + uin);
        // System.Console.WriteLine("pass_ticket=" + pass_ticket);
        // System.Console.WriteLine("key=" + key);
        // System.Console.WriteLine("appmsg_token=" + appmsg_token);

        var configFolder =
            _wechatFolderSection.GetSection(AppSettings.ConfigFolder).Value
            ?? throw new Exception($"{AppSettings.ConfigFolder}在appsettings.json没有发现");
        System.Console.WriteLine(configFolder);

        if (!Directory.Exists(configFolder))
            Directory.CreateDirectory(configFolder);

        var configFileName = $"config_{biz}.json";
        string configFilePath = Path.Combine(configFolder, configFileName);

        if (!Path.Exists(configFilePath))
        {
            string v1 = JsonConvert.SerializeObject(new OffsetConfig { Biz = biz, CurrnetOffset = 0 });
            File.WriteAllText(configFilePath, v1);
        }
        string configContent = File.ReadAllText(configFilePath);
        OffsetConfig offsetConfig = JsonConvert.DeserializeObject<OffsetConfig>(configContent) ?? throw new Exception("OffsetConfig is null");

        for (var i = offsetConfig.CurrnetOffset; i <= 10000; i += 10)
        {
            //更新offset
            offsetConfig.CurrnetOffset = i;
            string v1 = JsonConvert.SerializeObject(offsetConfig);
            File.WriteAllText(configFilePath, v1);
            // 请求响应
            var offset = i;
            string newUrl = GenerateNewUrl(offset, 10, biz, uin, pass_ticket, key, appmsg_token);
            System.Console.WriteLine(newUrl);
            string v = await RequestArticles(newUrl);
            System.Console.WriteLine(v);
            WeChatMessageResponse? articlResponseDto = JsonConvert.DeserializeObject<WeChatMessageResponse>(v);

            if (articlResponseDto == null)
                break;

            if (articlResponseDto.Ret == -3)
            {
                System.Console.WriteLine("Res=-3");
                offsetConfig.CurrnetOffset = i;
                string v2 = JsonConvert.SerializeObject(offsetConfig);
                File.WriteAllText(configFilePath, v2);
                break;
            }

            if (articlResponseDto.CanMessageContinue == 0)
            {
                System.Console.WriteLine("已经收集到底，无需再次收集,offset清理,重新来过");
                string v2 = JsonConvert.SerializeObject(new OffsetConfig { Biz = biz, CurrnetOffset = 0 });
                File.WriteAllText(configFilePath, v2);
                break;
            }
            GeneralMessageList generalMessageList =
                JsonConvert.DeserializeObject<GeneralMessageList>(articlResponseDto.GeneralMessageListJson)
                ?? throw new Exception("GeneralMessageList is null");
            // 现在您可以访问 generalMessageList.List 来获取消息列表
            var articleUrls = new List<string>();
            foreach (var article in generalMessageList.List)
            {
                if (article.AppMsgExtInfo == null)
                {
                    continue;
                }
                long timestamp = article.CommMsgInfo.Datetime;
                DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
                DateTime publishTime = dateTimeOffset.LocalDateTime;
                // System.Console.WriteLine(publishTime);
                // System.Console.WriteLine(article.AppMsgExtInfo.ContentUrl);
                articleUrls.Add(article.AppMsgExtInfo.ContentUrl);
                if (article.AppMsgExtInfo.IsMulti == 1)
                {
                    // System.Console.WriteLine("多文章信息");
                    foreach (var a in article.AppMsgExtInfo.MultiAppMsgItemList)
                    {
                        // System.Console.WriteLine(a.ContentUrl);
                        articleUrls.Add(a.ContentUrl);
                    }
                }
            }

            var JumpUrlCount = 0;
            if (articleUrls.Count == 0)
            {
                System.Console.WriteLine("请求失败,退出");
                break;
            }
            System.Console.WriteLine(articleUrls.Count);

            foreach (var url in articleUrls)
            {
                if (string.IsNullOrEmpty(url.Trim()))
                {
                    continue;
                }

                Uri myUri = new(url.Replace("&amp;amp;", "&").Replace("&amp;", "&"));

                NameValueCollection originalQueryCollection = HttpUtility.ParseQueryString(myUri.Query);
                string? mid = originalQueryCollection.Get("mid");
                string? idx = originalQueryCollection.Get("idx");
                string? sn = originalQueryCollection.Get("sn");
                System.Console.WriteLine($"biz = {biz}, mid= {mid}, idx={idx}, sn = {sn}");

                if (string.IsNullOrEmpty(biz) || string.IsNullOrEmpty(mid) || string.IsNullOrEmpty(idx) || string.IsNullOrEmpty(sn))
                    continue;
                List<Article> articles = _wechatDbContext
                    .Articles.Where(x => x.Mid == long.Parse(mid) && x.Biz == biz && x.Idx == int.Parse(idx))
                    .ToList();

                if (articles.Count > 0)
                {
                    System.Console.WriteLine($"跳过：mid = {mid},idx = {idx},url={url}");
                    JumpUrlCount += 1;
                    continue;
                }

                _wechatDbContext.Articles.Add(
                    new Article
                    {
                        Mid = long.Parse(mid),
                        Biz = biz,
                        Idx = int.Parse(idx),
                        Url = url
                    }
                );
                _wechatDbContext.SaveChanges();
                System.Console.WriteLine($"添加：mid = {mid},idx = {idx}添加成功");
            }

            System.Console.WriteLine($"有{JumpUrlCount}篇文章已经存在于数据库,当前offset={offset}");

            if (JumpUrlCount == articleUrls.Count)
            {
                System.Console.WriteLine($"系列文章已经全部存在于数据库，停止,该停止了,当前offset={offset}");
                break;
            }
            System.Console.WriteLine("等待三秒钟");
            await Task.Delay(3000);
        }
    }

    private static string GetLatestTxtFilePath()
    {
        string newestFilePath;
        string path = @"C:\Users\song\AppData\Local\Temp";
        var directoryInfo = new DirectoryInfo(path);
        FileInfo? newestFile = directoryInfo.GetFiles("*tmp.txt").OrderByDescending(f => f.CreationTime).FirstOrDefault();
        if (newestFile != null)
        {
            newestFilePath = newestFile.FullName;
        }
        else
        {
            newestFilePath = string.Empty;
        }
        return newestFilePath;
    }

    private static string GetLatestTxtFilePathV2()
    {
        string newestFilePath;
        string path = @"C:\Users\song\Downloads";
        var directoryInfo = new DirectoryInfo(path);
        FileInfo? newestFile = directoryInfo.GetFiles("*.txt").OrderByDescending(f => f.CreationTime).FirstOrDefault();
        if (newestFile != null)
        {
            newestFilePath = newestFile.FullName;
        }
        else
        {
            newestFilePath = string.Empty;
        }
        return newestFilePath;
    }

    private static (string biz, string uin, string pass_ticket, string key, string appmsg_token) ExtractParameters(string htmlContent)
    {
        string appmsg_token = htmlContent.Split(@"window.appmsg_token = """).Last().Split("\n").First().Replace(@""";", "").Trim();
        string key = htmlContent.Split(@"var key = """).Last().Split("\n").First().Replace(@""" || """";", "").Trim();
        string pass_ticket = htmlContent.Split(@"var pass_ticket = """).Last().Split("\n").First().Replace(@""" || """";", "").Trim();
        string uin = htmlContent.Split(@"var uin = """).Last().Split("\n").First().Replace(@""" || """";", "").Trim();
        string biz = htmlContent.Split(@"__biz: '").Last().Split("\n").First().Replace(@"',", "").Trim();
        return (biz, uin, pass_ticket, key, appmsg_token);
    }

    private static (string biz, string uin, string pass_ticket, string key, string appmsg_token) ExtractParametersV2(string htmlContent)
    {
        string appmsg_token = "";
        string key = string.Empty;
        string pass_ticket = string.Empty;
        string uin = string.Empty;
        string biz = string.Empty;
        if (htmlContent.Contains("POST https://mp.weixin.qq.com/mp/jsmonitor"))
        {
            var url = htmlContent.Split("HTTP/1.1").First().Split("POST").Last().Trim();
            Uri uri = new Uri(url);
            NameValueCollection queryParameters = HttpUtility.ParseQueryString(uri.Query);

            foreach (string k in queryParameters.AllKeys)
            {
                if (k == "appmsg_token")
                {
                    appmsg_token = queryParameters[k]!;
                }
                else if (k == "uin")
                {
                    uin = queryParameters[k]!;
                }
                else if (k == "__biz")
                {
                    biz = queryParameters[k]!;
                }
                else if (k == "pass_ticket")
                {
                    pass_ticket = queryParameters[k]!;
                }
                else if (k == "key")
                {
                    key = queryParameters[k]!;
                }
            }
        }
        else if (htmlContent.Contains("GET https://mp.weixin.qq.com/mp/geticon"))
        {
            var url = htmlContent.Split("Referer:").Last().Split("Accept-Encoding").First();
            System.Console.WriteLine(url);
            Uri uri = new Uri(url);
            NameValueCollection queryParameters = HttpUtility.ParseQueryString(uri.Query);

            foreach (string k in queryParameters.AllKeys)
            {
                if (k == "uin")
                {
                    uin = queryParameters[k]!;
                }
                else if (k == "__biz")
                {
                    biz = queryParameters[k]!;
                }
                else if (k == "pass_ticket")
                {
                    pass_ticket = queryParameters[k]!;
                }
                else if (k == "key")
                {
                    key = queryParameters[k]!;
                }
            }
            appmsg_token = htmlContent.Split("appmsg_token=").Last().Split("; pass_ticket=").First().Trim();
        }
        else if (htmlContent.Contains("GET https://mp.weixin.qq.com/mp/getbizbanner"))
        {
            var url = htmlContent.Split("HTTP/1.1").First().Split("GET").Last().Trim();
            Uri uri = new Uri(url);
            System.Console.WriteLine(url);
            System.Console.WriteLine("=======");
            NameValueCollection queryParameters = HttpUtility.ParseQueryString(uri.Query);

            foreach (string k in queryParameters.AllKeys)
            {
                if (k == "appmsg_token")
                {
                    appmsg_token = queryParameters[k]!;
                }
                else if (k == "uin")
                {
                    uin = queryParameters[k]!;
                }
                else if (k == "__biz")
                {
                    biz = queryParameters[k]!;
                }
                else if (k == "pass_ticket")
                {
                    pass_ticket = queryParameters[k]!;
                }
                else if (k == "key")
                {
                    key = queryParameters[k]!;
                }
            }
            biz = biz.Split(",").First();
        }
        else if (htmlContent.Contains("GET https://mp.weixin.qq.com/mp/relatedsearchword"))
        {
            var url = htmlContent.Split("HTTP/1.1").First().Split("GET").Last().Trim();
            Uri uri = new Uri(url);
            System.Console.WriteLine(url);
            System.Console.WriteLine("=======");
            NameValueCollection queryParameters = HttpUtility.ParseQueryString(uri.Query);

            foreach (string k in queryParameters.AllKeys)
            {
                if (k == "appmsg_token")
                {
                    appmsg_token = queryParameters[k]!;
                }
                else if (k == "uin")
                {
                    uin = queryParameters[k]!;
                }
                else if (k == "__biz")
                {
                    biz = queryParameters[k]!;
                }
                else if (k == "pass_ticket")
                {
                    pass_ticket = queryParameters[k]!;
                }
                else if (k == "key")
                {
                    key = queryParameters[k]!;
                }
            }
            biz = biz.Split(",").First();
        }
        else if (htmlContent.Contains("GET https://mp.weixin.qq.com/mp/profile_ext"))
        {
            var url = htmlContent.Split("HTTP/1.1").First().Split("GET").Last().Trim();
            Uri uri = new Uri(url);
            System.Console.WriteLine(url);
            System.Console.WriteLine("=======");
            NameValueCollection queryParameters = HttpUtility.ParseQueryString(uri.Query);

            foreach (string k in queryParameters.AllKeys)
            {
                if (k == "appmsg_token")
                {
                    appmsg_token = queryParameters[k]!;
                }
                else if (k == "uin")
                {
                    uin = queryParameters[k]!;
                }
                else if (k == "__biz")
                {
                    biz = queryParameters[k]!;
                }
                else if (k == "pass_ticket")
                {
                    pass_ticket = queryParameters[k]!;
                }
                else if (k == "key")
                {
                    key = queryParameters[k]!;
                }
            }
            biz = biz.Split(",").First();
        }

        return (biz, uin, pass_ticket, key, appmsg_token);
    }

    public static string GenerateNewUrl(long offset, int count, string biz, string uin, string pass_ticket, string key, string appmsg_token)
    {
        // 创建一个空的查询字符串实例
        NameValueCollection newQueryCollection = HttpUtility.ParseQueryString(string.Empty);
        // 添加参数
        newQueryCollection.Add("action", "getmsg");
        newQueryCollection.Add("__biz", biz);
        newQueryCollection.Add("f", "json");
        newQueryCollection.Add("offset", offset.ToString());
        newQueryCollection.Add("count", count.ToString());
        newQueryCollection.Add("is_ok", "1");
        newQueryCollection.Add("scene", "124");
        newQueryCollection.Add("uin", uin);
        newQueryCollection.Add("key", key);
        newQueryCollection.Add("pass_ticket", pass_ticket);
        newQueryCollection.Add("appmsg_token", appmsg_token);
        newQueryCollection.Add("wxtoken", string.Empty);
        newQueryCollection.Add("x5", "0");
        // 将查询字符串转换为字符串形式
        string? query = newQueryCollection.ToString();
        var newUrl = $"https://mp.weixin.qq.com/mp/profile_ext?{query}";
        return newUrl;
    }

    public static async Task<string> RequestArticles(string url)
    {
        var client = new HttpClient();

        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,

            RequestUri = new Uri(url),

            Headers =
            {
                { "host", "mp.weixin.qq.com" },
                {
                    "user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1301.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2875.116 Safari/537.36 NetType/WIFI MicroMessenger/7.0.5 WindowsWechat"
                },
                { "x-requested-with", "XMLHttpRequest" },
                { "accept", "*/*" },
                {
                    "referer",
                    "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIyODU3MzUzNA==&scene=124&uin=NDA4Mzg1NTk1&key=daf9bdc5abc4e8d09279856c85ab26663b0e996252fd607b2035c6db5ff6ab2c3e1e84d19704a7b17655085e77f37bffcf54bbd45d057c86f15cff8940697f997eeb46f73ddfffb2cabff6fb3172ca365a809c8bdd9b9658e11ab0a2eee1f64e0b97c00725713646c85dd157805fd263219bbbed79013f1cd1740092726a24cb&devicetype=Windows+10+x64&version=62090538&lang=zh_CN&a8scene=7&acctmode=0&pass_ticket=YzPgVcUQZmmEtdUZZh+9UodacIwMMAAkaFIFgqe8hnLbKuO53V4Pr0Es/hHANfsJ&winzoom=1"
                },
                // { "accept-language", @"zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.5;q=0.4" },
                {
                    "Cookie",
                    // "_qimei_q36=; _qimei_h38=b8adec6b92c108fed27e77a002000008e18519; ptcz=d8c5da24832349600236fb79c067637735acfb4f734f0568ef5e005a17d508a5; ua_id=Z0wM42FiH1ZytEYcAAAAAJEnQcIchzVfn-SDQZprZk0=; pgv_pvid=7684287875; mm_lang=zh_CN; suid=user_0_CptZNA4RxJWA1; _qimei_fingerprint=af9af71f6913167c78603752c3d6f100; _ga=GA1.2.2142936103.1738759999; _ga_8YVFNWD1KC=GS1.2.1738759998.1.0.1738759998.0.0.0; eas_sid=P1m773B8d942b5U5r8V8v108s6; fqm_pvqid=8dacc7db-ec4c-4faa-8a72-65461ec9aaee; omgid=0_CptZNA4RxJWA1; yyb_muid=07F7CD7191AA69BF08C0D9E09003688A; wxuin=52851319600173; _qimei_uuid42=1971e132f2b100265fe1165ed038ba9048bf0f49df; RK=ta94IGcfZr; _clck=3906292091|1|fyq|0; xid=2a6807f7708b4b4bb30b8f943adb181d; _hp2_id.1405110977=%7B%22userId%22%3A%221959381983892512%22%2C%22pageviewId%22%3A%222855723399794821%22%2C%22sessionId%22%3A%22616406155987143%22%2C%22identity%22%3Anull%2C%22trackerVersion%22%3A%224.0%22%7D; rewardsn=; poc_sid=HJ7Bs2ijwsDfjdpz2u9an89O85J5TgDG_yhoHE5k; wxtokenkey=777"
                    "wxuin=408385595; devicetype=android-33; version=2800315a; lang=zh_CN; pass_ticket=YzPgVcUQZmmEtdUZZh9UodacIwMMAAkaFIFgqe8hnLbKuO53V4Pr0Es/hHANfsJ; wap_sid2=CLvw3cIBEooBeV9IUDdmR1gyc1gzVFhWb3djVkRYWGdPejRGZDF0LXVrSHNoaHVONWthOWpBclZFU3MxMi13ZTAzbUNuUGRCNGFpekI3ZmEyUlR2Y3FWQzZKX0QxWEdDQk9VQUltYUJiUm9FU2dHZ1VCOWFrZW5PcmNFYnVUcWVVRjRjRTZpeTlxYmNOOFNBQUF+MMfe0rUGOA1AlU4="
                },
            },
        };

        using (var response = await client.SendAsync(request))
        {
            System.Console.WriteLine(response.StatusCode);
            System.Console.WriteLine(response.Headers);
            response.EnsureSuccessStatusCode();

            var body = await response.Content.ReadAsStringAsync();
            // Console.WriteLine(body);
            return body;
        }
    }
}
